<?php

namespace interface\v1;

/*
*发货检验类
*/

use control\optionSettingClass;

class shippingInspectionClass extends index
{
    private const page = 'shippingInspection';
    private const table = 'quality_order';
    private const title = '发货检验';

    /*列表-查询条件*/
    public function search()
    {
        $this->code = 1;
        $this->resp['data'] = [
            'orderNo' => '单据条码',
            'method' => find(['table' => 'quarantine_reason', 'field' => 'method as value, method as text', 'where' => " coid = '" . self::$coid . "'  "])['array'],
            'state' => ['待质检', '已质检'],
        ];
    }


    /*查询结果*/
    public function list()
    {
        //like查询数组
        $like = [
            "a.sourceNo" => $this->post('orderNo'),
            "b.code" => $this->post('code'),
            "b.materialName" => $this->post('materialName'),
        ];
        //全等查询数组
        $equal = [
            "a.targetId" => $this->post('khid'),
            'a.coid' => self::$coid,
        ];
        $and = " and a.type = 3";
        if ($this->post('createTime')) {
            $and .= self::timeComparison($this->post('createTime'), 'date', 'checkTime');
        }
        if ($this->post('reason')) {
            $and .= " and a.id in (select distinct orderId from quality_order_reason where coid = '" . self::$coid . "' and reasonId in (select id from quarantine_reason where coid = '" . self::$coid . "' and reason like '%" . $this->post('reason') . "%')) ";
        }
        if ($this->post('method')) {
            $and .= " and a.id in (select distinct orderId from quality_order_reason where coid = '" . self::$coid . "' and reasonId in (select id from quarantine_reason where coid = '" . self::$coid . "' and dealMethod = '" . $this->post('method') . "')) ";
        }
        if ($this->post('state')) {
            $and .= " and a.state = '{$this->post('state')}' ";
        } else {
            $and .= " and a.state = '待质检' ";
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        $page = $this->page(array("table" => self::table . " as a join material as b on a.materialId = b.id", 'field' => "a.*,b.name,b.code,b.model", "where" => $where, "order" => "a.time desc,a.list asc"));

        $data['title'] = ['id', "单据日期", "单据编号", "客户", "物料编码", '物料名称', '规格型号', '单位', '批次', '完工数量', '合格数量', '不良数量', '状态', '质检日期', '创建时间'];
        $data['result'] = [];
        foreach ($page['array'] as $array) {
            $kehu = query('kehu', "khid = '$array[targetId]'");
            $saleSendOrder = query('sale_send_order', "id = '$array[sourceId]'");
            $data['result'][] = [
                "id" => $array['id'],
                'recordDate' => $saleSendOrder['recordDate'], //单据日期
                'sourceNo' => $array['sourceNo'], // 单据编号
                'companyName' => $kehu['companyName'], //客户
                'code' => $array['code'], //物料编码
                'name' => $array['name'], //物料名称
                'model' => $array['model'], //规格型号
                'material' => $array['name'] . ($array['model']?' - ' .$array['model'] :''),
                'unit' => $array['unit'], //单位
                'batch' => $array['batch'], // 批次
                'num' => self::lostZero($array['num'], 'numPrecision'), //完工数量
                'passNum' => self::lostZero($array['passNum'], 'numPrecision'), //合格数量
                'badNum' => $array['state'] == '待质检' ? 0 : $array['num'] - $array['passNum'], //不良数量
                "state" => $array['state'],
                'checkTime' => $array['checkTime'],
                'time' => self::formatDate($array['time'], 'Y/m/d'),
            ];
        }
        $data['page'] = $page['para'];
        //返回
        $this->code = 1;
        $this->resp['data'] = $data;
    }


    /**
     * 提交
     *
     * @return bool|string
     */
    public function detailEdit()
    {
        $detail = !empty($_POST['detail']) ? json_decode($_POST['detail'], true) : [];
        $id = $this->post('id');
        $itemTextArr = $this->post('itemText');
        $itemIdArr = $this->post('resultOption') ? array_keys($this->post('resultOption')) : [];
        $resultOptionArr = $this->post('resultOption');
        $reasonIdArr = inStockClass::getArrVal('reasonOptionId', $detail);
        $reasonNumArr = inStockClass::getArrVal('reasonNum', $detail);
        $mxTextArr = inStockClass::getArrVal('mxText', $detail);
        $field = [
            'state' => '已质检',
            'checkId' => self::$stid,
            'checkTime' => $this->time,
            'passNum' => $this->post('passNum') ? self::formattingFigure($this->post('passNum'), 'numPrecision') : '',
        ];
        $annotation = [
            'passNum' => '合格数量',
        ];
        $rules = [
            'passNum' => 'required|numeric',
        ];
        // 校验是否符合规则
        $vt = new \verify();
        $result = $vt->setAliases($annotation)->validate($field, $rules)->isOk();
        if ($result === false) {
            $this->resp['warn'] = $vt->getErrs()[0];  // 多个规则提示最前面一条
            goto resp;
        }
        $where = " id = '$id' ";
        $info = query(self::table, $where);
        //判断
        if (!$this->power(self::page, "edit")) {
            $this->resp['warn'] = "你没有编辑" . self::title . "的权限";
        } elseif (static::is_null_array($itemIdArr)) {
            $this->resp['warn'] = '未找到质检项目';
        } elseif (static::is_null_array($resultOptionArr)) {
            $this->resp['warn'] = '请选择结果选项';
        } elseif (!empty($reasonIdArr) && static::is_null_array($reasonNumArr)) {
            $this->resp['warn'] = '请填写不良数量';
        } elseif (empty($info['id'])) {
            $this->resp['warn'] = '未找到此发货检验单';
        } elseif ($info['state'] !== '待质检') {
            $this->resp['warn'] = '此发货检验单不是待质检状态，不能编辑';
        } elseif ($info['num'] < $field['passNum']) {
            $this->resp['warn'] = '合格数量超出了总数量';
        } elseif (round(array_sum($reasonNumArr), 2) != round(($info['num'] - $field['passNum']), 2)) {
            $this->resp['warn'] = '不良明细中数量之和不等于总的不良数量';
        } else {
            $this->resp['warn'] = '';
            //判断属于生产计划单的数量是否超过总数量
            foreach ($reasonNumArr as $k => $val) {
                if ($val > $info['num'] - $field['passNum']) {
                    $this->resp['warn'] = "不良明细中不良数量和超过了总的不良数量";
                    break;
                }
            }
            if (empty($this->resp['warn'])) {
                $this->startTrans();
                $isPass = true;//事务通过标志
                $this->resp['warn'] = static::update([
                    "table" => self::table,
                    "field" => $field,
                    "where" => $where,
                ]);
                foreach ($itemIdArr as $nid) {
                    $mx = query(self::table . "_item", "id = '$nid'");
                    if ($mx['id']) {
                        $warn = static::update([
                            "table" => self::table . "_item",
                            "field" => [
                                'options' => $resultOptionArr[$nid],
                                'text' => $itemTextArr[$nid],
                            ],
                            "where" => " id = '$nid'",
                        ]);
                        if (!in_array($warn, ['新增成功', '更新成功'])) {
                            $isPass = false;
                            $this->resp['warn'] = $warn;
                            break;
                        }
                    }
                }
                //添加或更新质检不良原因
                if (is_array($reasonIdArr)) {
                    $reasonOptionArr = $reasonIdArr;
                    foreach ($reasonIdArr as $k => $nid) {
                        $mx = query(self::table . "_reason", "id = '$nid'");
                        $quarantine_reason = query('quarantine_reason', "id = '$reasonOptionArr[$k]'");
                        $reasonNumArr[$k] = self::formattingFigure($reasonNumArr[$k], 'numPrecision');
                        if (!empty($mx['id'])) {
                            //更新
                            $warn = static::update([
                                "table" => self::table . "_reason",
                                "field" => [
                                    'reasonId' => $reasonOptionArr[$k],
                                    'num' => $reasonNumArr[$k],
                                    'dealMethod' => $quarantine_reason['method'],
                                    'text' => $mxTextArr[$k],
                                ],
                                "where" => " id = '$nid'",
                            ]);
                        } else {
                            //新增
                            $warn = static::insert([
                                "table" => self::table . "_reason",
                                "field" => [
                                    'id' => $nid,
                                    'orderId' => $id,
                                    'coid' => self::$coid,
                                    'reasonId' => $reasonOptionArr[$k],
                                    'num' => $reasonNumArr[$k],
                                    'dealMethod' => $quarantine_reason['method'],
                                    'text' => $mxTextArr[$k],
                                ],

                            ]);
                        }
                        if (!in_array($warn, ['新增成功', '更新成功'])) {
                            $isPass = false;
                            $this->resp['warn'] = $warn;
                            break;
                        }
                    }
                }

                if (in_array($this->resp['warn'], ["新增成功", "更新成功"]) && $isPass) {
                    $this->commitTrans();
                    delete(array('table' => self::table . "_reason", 'where' => " id not in ('" . implode("','", $reasonIdArr) . "') and orderId = '$id'"));
                    //判断此订单所有批次是否都检验完了，如果检验完成，则修改入库单质检状态为已质检
                    if (static::total(array('table' => self::table, "where" => "state = '待质检' and sourceId ='$info[sourceId]' and coid = '" . self::$coid . "'")) == 0) {
                        update(array('table' => 'inventory', 'field' => ['workFlow' => '已质检'], 'where' => "sourceId = '$info[sourceId]' and classify = 1 and coid = '" . self::$coid . "'"));
                    }
                    auditingFollow(array(
                        "type" => "发货检验单",
                        "typeId" => $info['id'],
                        "text" => "【{$this->control['name']}】确认",
                    ));
                    //添加日志
                    $type = mb_substr($this->resp['warn'], 0, 2, 'utf-8');
                    $text = $this->control['name'] . $type . "了" . self::title . " id：【" . $id . '】';
                    $this->logText(["type" => self::page, "text" => $text]);
                    //返回
                    $this->code = 1;
                } else {
                    $this->rollback();
                }
            }
        }

        resp:
    }


    /*详情页*/
    public function detail()
    {
        $info = query(self::table, " id = '{$this->post('id')}'");
        if (empty($info['id'])) {
            $this->resp['warn'] = '未找到此' . self::title;
        } else {
            /*****质检项目********/
            $quarantineItem['title'] = ['质检项', '检验标准', '结果选项', '备注'];
            $result = find(array('table' => self::table . "_item", 'where' => "orderId = '$info[id]' order by list"));
            $quarantineItem['result'] = [];
            foreach ($result['array'] as $array) {
                $quarantine_item = query('quarantine_item', "id = '$array[itemId]'");
                $quarantineItem['result'][] = [
                    'itemId' => $array['id'],
                    'name' => $quarantine_item['name'],
                    'standard' => $quarantine_item['standard'],
                    'option' => explode('，', $quarantine_item['result']),
                    'checked' => $array['options'],
                    'itemText' => $array['text'],
                ];
            }
            /*****不良原因********/
            $reason['title'] = ['不良原因', '不良数量', '处置方式', '备注', '状态', '处理人', '处理日期', '操作'];
            $result = find(array('table' => self::table . "_reason", 'where' => "orderId = '$info[id]' order by list"));
            $reason['result'] = [];
            $reason['option'] = find([
                'table' => 'quarantine_reason',
                'where' => " coid = '" . self::$coid . "' and orderId = '$info[qid]' order by list asc ",
                'field' => ' id as value,  reason as text',
            ])['array'];
            foreach ($result['array'] as $array) {
                $quarantine_reason = query('quarantine_reason', " id = '{$array['reasonId']}' ");
                $reason['result'][] = [
                    'reasonId' => $array['id'],
                    'reasonOption' => $quarantine_reason['name'],
                    'reasonOptionId' => $array['reasonId'],
                    'reasonNum' => self::lostZero($array['num'], 'numPrecision'),
                    'mxText' => $array['text'],
                    'state' => $array['state'],
                    'dealStaff' => self::findStaff($array['dealId']),
                    'dealDate' => self::null($array['dealDate']),
                ];
            }
            $kehu = query('kehu', "khid = '$info[targetId]'");
            $source = query($info['sourceTable'], "id = '$info[sourceId]'");
            $material = query('material', "id = '$info[materialId]'");
            $quarantine = query('quarantine', "id = '$info[qid]'");
            $setting = optionSettingClass::getSetting('质量');
            if ($info['updateTime'] == $info['time'] && $info['state'] == '待质检' && isset($setting['checkOrderDefault']['val']) && $setting['checkOrderDefault']['val'] == '单据数量') {
                $info['passNum'] = $info['num'];
            }
            $this->resp['data'] = [
                'info' => [
                    "id" => $info['id'],
                    'recordDate' => $source['recordDate'], //单据日期
                    'sourceNo' => $info['sourceNo'], // 单据编号
                    'companyName' => $kehu['companyName'], //客户
                    'code' => $material['code'], //物料编码
                    'name' => $material['name'], //物料名称
                    'model' => $material['model'], //规格型号
                    'material' => $material['code'] . '-' . $material['name'] . '-' . $material['model'],
                    'batch' => $info['batch'], // 批次
                    'unit' => $info['unit'], //单位
                    'num' => self::lostZero($info['num'], 'numPrecision'), //完工数量
                    'passNum' => self::lostZero($info['passNum'], 'numPrecision'), //合格数量
                    'badNum' => $info['state'] == '待质检' ? 0 : $info['num'] - $info['passNum'], //不良数量
                    "state" => $info['state'],
                    'checkTime' => $info['checkTime'],
                    'time' => self::formatDate($info['time'], 'Y/m/d'),
                ],
                'quality' => [
                    "qualityType" => $quarantine['qualityType'],
                    "proportionRate" => ($quarantine['proportion'] * 100) . '%',
                    "proportionNum" => $info['num'] * $quarantine['proportion'],
                    'mandate' => $quarantine['mandate'],
                ],
                'quarantine' => $quarantineItem,
                'reason' => $reason,
                'system' => [
                    "orderNo" => $info['orderNo'],
                    "checkStaff" => self::findStaff($info['checkId']),
                    "checkId" => $info['checkId'],
                    "checkTime" => $info['checkTime'],
                ],
            ];
            $this->code = 1;
        }
    }

    /**
     * 撤回
     */
    public function cancel()
    {
        $id = $this->post('id');
        $info = query(self::table, " id = '$id'");
        $field = [
            'state' => '待质检',
            'checkId' => '',
            'checkTime' => '',
        ];
        if (!$this->power(self::page, 'cancel')) {
            $this->resp['warn'] = '你还没有撤回权限';
        } elseif (empty($info['id'])) {
            $this->resp['warn'] = '未找到此质检单';
        } elseif ($info['state'] != '已质检') {
            $this->resp['warn'] = '此质检单不是已质检状态，无需撤回';
        } elseif (static::total(array('table' => 'quality_order_reason', 'where' => "orderId = '$id' and state = '已处理'")) > 0) {
            $this->resp['warn'] = '此发货检验单已处理，不能撤回';
        } elseif (static::total(array('table' => 'inventory', 'where' => "sourceId = '$info[sourceId]' and state != '待出库' and classify = 0 and coid = '" . self::$coid . "'")) > 0) {
            $this->resp['warn'] = '此发货检验单对应的出库单已出库，不能撤回';
        } else {
            $this->resp['warn'] = update(array(
                "table" => self::table,
                "field" => $field,
                "where" => "id = '$info[id]'",
            ));
            if (in_array($this->resp['warn'], ["新增成功", "更新成功"])) {
                update(array('table' => 'inventory', 'field' => ['workFlow' => '待质检'], 'where' => "sourceId = '$info[sourceId]' and classify = 0 and coid = '" . self::$coid . "'"));
                auditingFollow(array(
                    "type" => "发货检验单",
                    "typeId" => $info['id'],
                    "text" => "【{$this->control['name']}】撤回",
                ));
                //添加日志
                $type = mb_substr($this->resp['warn'], 0, 2, 'utf-8');
                $text = $this->control['name'] . $type . "了" . self::title . "id：【" . $id . '】';
                $this->logText(["type" => self::page, "text" => $text]);
                $this->code = 1;
            }
        }

        resp:
    }


}
